package com.yangrong.userservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.yangrong.common.constant.UserServiceConstant;
import com.yangrong.common.exception.ErrorCodeEnum;
import com.yangrong.common.utils.R;
import com.yangrong.userservice.dao.TbUserDao;
import com.yangrong.userservice.entity.TbUserEntity;
import com.yangrong.userservice.entity.LoginRequestBean;
import com.yangrong.userservice.service.TbUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yangrong.common.utils.PageUtils;
import com.yangrong.common.utils.Query;


@Service("tbUserService")
public class TbUserServiceImpl extends ServiceImpl<TbUserDao, TbUserEntity> implements TbUserService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TbUserEntity> page = this.page(
                new Query<TbUserEntity>().getPage(params),
                new QueryWrapper<TbUserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R checkLogin(LoginRequestBean request) {
        TbUserEntity selectEntity = new TbUserEntity();
        TbUserEntity resultEntity = new TbUserEntity();
        String username;
        String password;
        String phone;
        String code;

        if ("password".equals((String) request.getType())) {
            username = (String) request.getUsername();
            password = (String) request.getPassword();
            if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
                selectEntity.setUsername(username);
                resultEntity = baseMapper.selectOne(new QueryWrapper<>(selectEntity));
                if (resultEntity == null) {
                    return R.error(ErrorCodeEnum.LOGIN_FAILED_NO_USER.getCode(), ErrorCodeEnum.LOGIN_FAILED_NO_USER.getMsg());
                } else {
                    if (StringUtils.isNotBlank(resultEntity.getPassword()) && resultEntity.getPassword().equals(password)) {
                        stringRedisTemplate.opsForValue().set("userId:" + resultEntity.getUsername(), String.valueOf(resultEntity.getId()));
                        return R.ok().put("userInfo", resultEntity);
                    } else {
                        return R.error(ErrorCodeEnum.LOGIN_FAILED_ERROR_PASSWORD.getCode(), ErrorCodeEnum.LOGIN_FAILED_ERROR_PASSWORD.getMsg());
                    }
                }
            } else {
                return R.error(ErrorCodeEnum.LOGIN_PARAMS_EXCEPTION.getCode(), ErrorCodeEnum.LOGIN_PARAMS_EXCEPTION.getMsg());
            }
        } else if ("smscode".equals((String) request.getType())) {
            phone = (String) request.getPhone();
            code = (String) request.getCode();

            if (StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(code)) {
                String redisCode = stringRedisTemplate.opsForValue().get(UserServiceConstant.SMS_LOGIN_CODE_CACHE_PREFIX + phone);
                if (!redisCode.split("_")[0].equals(code)) {
                    return R.error(ErrorCodeEnum.LOGIN_PARAMS_SMS_CODE_EXCEPTION.getCode(), ErrorCodeEnum.LOGIN_PARAMS_SMS_CODE_EXCEPTION.getMsg());
                } else {
                    selectEntity.setPhone(phone);
                    resultEntity = baseMapper.selectOne(new QueryWrapper<>(selectEntity));
                    if (resultEntity == null) {
                        return R.error(ErrorCodeEnum.LOGIN_FAILED_NO_USER.getCode(), ErrorCodeEnum.LOGIN_FAILED_NO_USER.getMsg());
                    } else {
                        stringRedisTemplate.opsForValue().set("userId:" + resultEntity.getUsername(), String.valueOf(resultEntity.getId()));
                        return R.ok().put("userInfo", resultEntity);
                    }
                }
            }
        }
        return R.error(ErrorCodeEnum.UNKNOW_EXCEPTION.getCode(), ErrorCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }

    @Override
    public boolean findUserPhone(String phone) {
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("phone", phone);
        if (baseMapper.selectByMap(searchMap).size() > 0) {
            return true;
        }

        return false;
    }

    @Override
    public void updateUserInfo(Map<String, Object> params) {
        String userId = stringRedisTemplate.opsForValue().get("userId:" + params.get("username"));
        String nickname = (String) params.get("nickname");
        String avatar = (String) params.get("image");

        TbUserEntity userEntity = new TbUserEntity();
        userEntity.setId(Long.parseLong(userId));
        userEntity.setNickname(nickname);
        userEntity.setAvatar(avatar);

        baseMapper.updateById(userEntity);
    }

}